package com.example.day25_camera2pic;

import android.content.Context;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.os.Environment;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import androidx.annotation.NonNull;

/**
 * Description:
 * Created by Gdu on 2021/1/2 21:28.
 */

@SuppressWarnings("deprecation")
public class CameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback, Camera.PreviewCallback {

    private Camera mCamera;
    private Camera.Size size;
    private byte[] buffer,nv21_rotate;

    public CameraSurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        getHolder().addCallback(this);
    }

    @Override
    public void surfaceCreated(@NonNull SurfaceHolder holder) {
        startPreview();
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

    }
        
    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {

    }

    private void startPreview() {
        try {
            mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
        } catch (Exception e) {
            Log.e("CameraSurfaceView","不能打开相机  "+e.getMessage());
            e.printStackTrace();
            return;
        }
        Camera.Parameters parameters = mCamera.getParameters();
        size = parameters.getPreviewSize();
        try {
            mCamera.setPreviewDisplay(getHolder());
            mCamera.setDisplayOrientation(90);//默认的相机是横着的，所以要旋转90°
            buffer = new byte[size.width * size.height * 3 / 2];//一帧yuv的大小是尺寸的3/2
            nv21_rotate = new byte[size.width * size.height * 3 / 2];//一帧yuv的大小是尺寸的3/2
            mCamera.addCallbackBuffer(buffer);
            mCamera.setPreviewCallbackWithBuffer(this);
            mCamera.startPreview();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private volatile boolean isCaptrue;
    public void startCaptrue(){
        isCaptrue=true;
    }

    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {
        if (isCaptrue) {
//            YuvUtils.portraitData2Raw(data,buffer,size.width,size.height);
            YuvUtils.nv21_rotate_to_90(data,nv21_rotate,size.width,size.height);//旋转YUV图片
            isCaptrue=false;
            captrue(nv21_rotate);
        }
        mCamera.addCallbackBuffer(data);
    }

    int index = 0;
    public void captrue(byte[] temp){

        //保存一张照片
        String fileName = "IMG_" + String.valueOf(index++) + ".jpg";  //jpeg文件名定义
        File sdRoot = Environment.getExternalStorageDirectory();    //系统路径

        File pictureFile = new File(sdRoot,   fileName);
        if (!pictureFile.exists()) {
            try {
                pictureFile.createNewFile();

                FileOutputStream filecon = new FileOutputStream(pictureFile);
//ImageFormat.NV21 and ImageFormat.YUY2 for now
                YuvImage image = new YuvImage(temp, ImageFormat.NV21,size.height, size.width,null);   //将NV21 data保存成YuvImage
                //图像压缩
                image.compressToJpeg(
                        new Rect(0, 0, image.getWidth(), image.getHeight()),
                        100, filecon);   // 将NV21格式图片，以质量70压缩成Jpeg，并得到JPEG数据流

            }catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

}
